from rest_framework import serializers
from . import models
from rest_framework.exceptions import APIException


# class ArticleContentSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = models.ArticleContent
#         fields = ['content']


class ArticleListSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = ['id', 'title', 'pic', 'date_add', 'date_update', 'is_active', 'is_recommend', 'sort', 'admin']
        read_only_fields = ['id', 'title', 'pic', 'date_add', 'date_update', 'is_active', 'is_recommend', 'sort',
                            'admin']

    sort = serializers.SerializerMethodField(read_only=True)

    def get_sort(self, obj):
        return obj.sort.name

    admin = serializers.SerializerMethodField(read_only=True)

    def get_admin(self, obj):
        return obj.admin.name


class AdminArticleSerializer(serializers.ModelSerializer):
    content = serializers.CharField(allow_blank=True,allow_null=True)

    class Meta:
        model = models.Article

        fields = ['id', 'title', 'shorter', 'keywords', 'description', 'pic', 'date_add', 'date_update', 'is_active',
                  'is_recommend', 'sort', 'admin', 'content']

        extra_kwargs = {
            'id': {'read_only': True},
            'date_add': {'read_only': True},
            'date_update': {'read_only': True},
            'admin': {'read_only': True}
        }

    def create(self, validated_data):
        request = self.context.get('request')
        admin_id = request.user.get('id')
        validated_data['admin_id'] = admin_id
        content = validated_data.pop('content')
        article = models.Article.objects.create(**validated_data)
        models.ArticleContent.objects.create(content=content, article=article)
        return article

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title')
        instance.shorter = validated_data.get('shorter')
        instance.keywords = validated_data.get('keywords')
        instance.description = validated_data.get('description')
        instance.pic = validated_data.get('pic')
        instance.is_active = validated_data.get('is_active')
        instance.is_recommend = validated_data.get('is_recommend')
        instance.sort = validated_data.get('sort')
        instance.save()
        models.ArticleContent.objects.filter(article=instance).update(content=validated_data.get('content'))
        return instance
